import axios from "axios";
import vm from "../main";
import qs from "qs";
import router from "@/router/index";
import Tools from "@/tools/utils";
/* 全局默认配置 */
var http = axios.create({
  // baseURL: '',
  timeout: 60000
});

/* 请求拦截器 */
http.interceptors.request.use(
  config => {
    const token = Tools.getCookie("UID");
    config.headers.token = token;

    if (!config.hideLoading) {
      vm.$toast.clear();
      vm.showLoading("加载中");
    }

    // 默认携带参数
    const defaultParams = {};
    // defaultParams.xxx = xxx

    if (config.method === "get") {
      if (config.params) {
        config.params = Object.assign({}, config.params, defaultParams);
      } else {
        config.params = defaultParams;
      }
    } else if (config.method === "post") {
      let data = null;
      if (config.data) {
        data = Object.assign({}, config.data, defaultParams);
      } else {
        data = defaultParams;
      }
    }
    return config;
  },
  error => {
    vm.$toast.clear();
    Promise.reject(error);
  }
);

http.interceptors.response.use(
  // 拦截返回response
  response => {
    vm.$toast.clear();
    const res = response.data;
    if (res && (res.code === 0 || res.code === "0")) {
      return Promise.resolve(res.result || res);
    } else if (res && res.result_code === 555) {
      vm.$toast("登录过期");
      router.replace({ name: "home" });
      Tools.clearCookie();
    } else if (res.message) {
      vm.$toast(res.message);
    }
    return Promise.reject(res);
  },
  error => {
    console.log(error);
    const errText = error.response.data.errtext;
    vm.$toast.clear();
    if (errText) {
      vm.$toast(errText);
    }
    return Promise.reject(error);
  }
);

export default http;
